<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>this指向</title>
</head>
<body>
    
</body>
<script>
    //this是一个对象, 指的是当前代码执行的上下文

    //1. 在function声明的方法中, 谁调用this所在的方法, 就指向谁
    console.log("1 window === this: ", window === this)  // true
    function fun1(){
        console.log("1 ", window === this)          // true
    }
    fun1()    //这时候执行fun1() === window.fun1()  this就指向window

    //2. 在function声明的方法中, 谁调用this所在的方法, 就指向谁
    let obj1 = {
        sub1: {
            fun1: function () {
                console.log("2 ", obj1.sub1 === this)
            }
        }
    }
    obj1.sub1.fun1()  // obj1.sub1这个对象调用了 this所在的方法, this就指向 obj1.sub1

    //3. 
    let obj2 = {  
        sub2: {
            fun2: () => {  //this没有改变, 调用方法前this指向谁, 调用方法后还是指向谁
                console.log("3 ", this === window)
            }
        },
        sub3: function () {  // 调用sub3方法时, this会指向obj2
            let ob = () => {  
                console.log("4 ", this === obj2)  // 调用sub3方法时, this会指向obj2;  而箭头函数不会改变this指向, 这里this = obj2
            }
            ob()
        }
    }
    obj2.sub2.fun2()
    obj2.sub3()

    //改变this指向的三个方法的区别: apply, call, bind
    /**
     * apply: 改变this指向并立即执行函数,传参需数组形式
     * call:  改变this指向并立即执行函数
     * bind:  改变this, 后面加上()才能执行
    */
    let obj3 = {
        fun3: function (arg1, arg2) {
            console.log("参数1:",arg1,"  参数2:", arg2)
            console.log("this => ", this)
        }
    }
    obj3.fun3.apply({a:123},["apply","B"])
    obj3.fun3.call({a:456},"call","B")
    obj3.fun3.bind({a:678},"bind","B")()

</script>
</html>